/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package br.jm.mala.relatorio;

import br.jm.mala.util.Conecta;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JRParameter;
import net.sf.jasperreports.engine.JasperRunManager;
import net.sf.jasperreports.engine.fill.JRAbstractLRUVirtualizer;
import net.sf.jasperreports.engine.fill.JRGzipVirtualizer;

/**
 *
 * @author joao
 */
public class relatorio extends HttpServlet {

    private static final long serialVersionUID = 7110300149328642655L;

    /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
     * methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) {
        ServletOutputStream servletOutputStream = null;
        InputStream reportStream = null;
        Conecta conecta = null;

        try {
            processRequest(request, response);

            servletOutputStream = response.getOutputStream();

            ServletContext context = getServletContext();
            HttpSession session = request.getSession(false);

            Map parametros = new HashMap();

            String cWhere = "";
            String cOrder = "";
            String caminho = "/WEB-INF/relatorios/";
            String relatorio = "";

            String cTipRel = request.getParameter("tipRel");
            String tipAcionista = request.getParameter("tipAcionista");
            String tipFiltro = request.getParameter("tipFiltro");
            String filtro = request.getParameter("filtro");
            String order = request.getParameter("order");
            String orderTipo = request.getParameter("orderTipo");
            Map<String, String[]> cLista = request.getParameterMap();
            String cTipoTransf = request.getParameter("tipoTransf");

            String impPartic;
            String impProposta;
            String impObs;

            if (cTipRel.equals("categoria")) {
                relatorio = caminho.concat("relCategoria.jasper");
                /*
                 tipAcionista = (String) session.getAttribute("tipAcionista");
                 tipFiltro = (String) session.getAttribute("tipFiltro");
                 filtro = (String) session.getAttribute("filtro");
                 order = (String) session.getAttribute("order");

                 if (!tipAcionista.equals("T")) {
                 cWhere = "WHERE cliente.\"tip_cliente\" = '".concat(tipAcionista).concat("' ");
                 }
                 if (order.equals("C")) {
                 cOrder = "ORDER BY cliente.\"num_cpf\" ";
                 } else {
                 cOrder = "ORDER BY cliente.\"nom_cliente\" ";
                 }
                 */
            }

            //String arquivo = context.getRealPath(relatorio);
            String dirsub = context.getRealPath(caminho);

            conecta = new Conecta();

            JRAbstractLRUVirtualizer virtualizer = new JRGzipVirtualizer(100);

            reportStream = getServletConfig().getServletContext().getResourceAsStream(relatorio);

            if (!cWhere.isEmpty()) {
                parametros.put("PAR_WHERE", cWhere);
            }
            if (!cOrder.isEmpty()) {
                parametros.put("PAR_ORDER", cOrder);
            }
            //String rootDir = context.getContextPath().concat("/images/logo_SA_1.jpg");
            parametros.put(JRParameter.REPORT_VIRTUALIZER, virtualizer);
            parametros.put("SUBREPORT_DIR", dirsub.concat(File.separator));
            //parametros.put("LOGO", dirsub.concat("\\logo_SA_1.jpg"));
            parametros.put("REPORT_LOCALE", new Locale("pt", "BR"));

            //para gerar o relatório em PDF
            // o método runReportToPdfStream foi usado
            JasperRunManager.runReportToPdfStream(reportStream, servletOutputStream, parametros, conecta.Conecta());

            // envia o relatório em formato PDF para o browser
            response.setContentType("application/pdf");

        } catch (SQLException ex) {
            Logger.getLogger("global").log(Level.SEVERE, null, ex);
        } catch (ServletException ex) {
            Logger.getLogger(relatorio.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(relatorio.class.getName()).log(Level.SEVERE, null, ex);
        } catch (JRException e) {
            StringWriter stringWriter = new StringWriter();
            PrintWriter printWriter = new PrintWriter(stringWriter);
            e.printStackTrace(printWriter);
            response.setContentType("text/plain");
            try {
                response.getOutputStream().print(stringWriter.toString());
            } catch (IOException ex) {
                Logger.getLogger(relatorio.class.getName()).log(Level.SEVERE, null, ex);
            }
        } finally {
            try {
                servletOutputStream.flush();
                servletOutputStream.close();
                reportStream.close();
                try {
                    conecta.close();
                } catch (SQLException ex) {
                    Logger.getLogger(relatorio.class.getName()).log(Level.SEVERE, null, ex);
                }
            } catch (IOException ex) {
                Logger.getLogger(relatorio.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}
